package com.ys.peony.ui.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.ys.peony.R;
import com.ys.peony.app.YSConstant;
import com.ys.peony.enums.BusinessDetailStatus;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.interfaces.IsearchView;
import com.ys.peony.model.CarModel;
import com.ys.peony.model.JiekuanrenModel;
import com.ys.peony.model.JiekuanrenResp;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.StringUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yklab.library.refreshlayout.adapters.CommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.inter.OnClickCommonListener;

/**
 * 统一搜索页面
 * Created by 59153 on 2017/8/22.
 */

public class CommonSearchView extends FrameLayout implements OnClickCommonListener,IsearchView<JiekuanrenModel> {

    public final static int CARPLEDGE_TYPE = 1; //抵押物
    public final static int MIANSHENG_TYPE = 2; //免审
    public final static int BUJIAN_TYPE = 3; // 补件
    public final static int BUJIANDAHUI_TYPE = 4; //打回补件
    private RecyclerView search_list;
    private FrameLayout search_layout;
    private CommonRecyclerViewAdapter mAdapter;
    private List<JiekuanrenModel> mList;
    private LinearLayoutManager mLayoutManager;
    private Context mContext;
    private int curItemType = YSConstant.INVALID;

    private ViewItemListener mViewItemListener = null;

    public CommonSearchView(Context context) {
        super(context);
        init(context, null);
    }

    public CommonSearchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }


    public CommonSearchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        initView(attrs);
        initListener();
        setAdapter();
    }

    private void initView(AttributeSet attrs) {
        LayoutInflater.from(mContext).inflate(R.layout.view_search_layout, this);
        search_list = (RecyclerView) findViewById(R.id.search_list);
        search_layout = (FrameLayout) findViewById(R.id.search_layout);
    }

    private void initListener() {
        mList = new ArrayList<>();
        mLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mAdapter = new CommonRecyclerViewAdapter<JiekuanrenModel>(mContext, mList, R.layout.view_cartpledge_item) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
                super.onBindViewHolder(holder, position);
                if (!isFooterView(position)) {
                    CarModel carModel = null;
                    JiekuanrenModel model = mList.get(position);
                    if (model == null) {
                        return;
                    }
                    if (model.getVehicleList().size() > 0) {
                        carModel = model.getVehicleList().get(model.getVehicleList().size() - 1);
                    }
                    ((CommonRecyclerViewHolder) holder)
                            .setText(R.id.tv_name, StringUtils.isEmpty(model.getClientName()) ? "" : model.getClientName())
                            .setText(R.id.tv_customerType, model.getClientClassfyName())
                            .setText(R.id.tv_businessType, BusinessDetailStatus.getStatus(model.getLoanStatus()))
                            .setText(R.id.tv_businessNum, model.getSerialNumber());
                    if (null != carModel) {
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carNum, StringUtils.isEmpty(carModel.getPlate_number()) ? "" : carModel.getPlate_number());
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carBrand, StringUtils.isEmpty(carModel.getBrand_name()) ? "" : carModel.getBrand_name());
                    } else {
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carNum, "");
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carBrand, "");
                    }
                    ((CommonRecyclerViewHolder) holder).setViewListener(R.id.basicinfo_rl);
                    ((CommonRecyclerViewHolder) holder).setViewListener(R.id.diyawu_rl);
                    ((CommonRecyclerViewHolder) holder).setViewListener(R.id.item);
                    LinearLayout linearLayout = ((CommonRecyclerViewHolder) holder).getView(R.id.guarantee);
                    if (curItemType == CARPLEDGE_TYPE) {
                        linearLayout.setVisibility(VISIBLE);
                    } else {
                        linearLayout.setVisibility(GONE);
                    }
                    if (curItemType == MIANSHENG_TYPE) {
                        ((CommonRecyclerViewHolder) holder).setImgResource(R.id.jiekuan_icon, R.mipmap.miansheng_icon);
                    } else if (curItemType == BUJIAN_TYPE) {
                        ((CommonRecyclerViewHolder) holder).setImgResource(R.id.jiekuan_icon, R.mipmap.repair);
                    } else if (curItemType == BUJIANDAHUI_TYPE) {
                        ((CommonRecyclerViewHolder) holder).setImgResource(R.id.jiekuan_icon, R.mipmap.repairback);
                    }
                }
            }
        };
        mAdapter.isHasFooter(false);
        mAdapter.setOnClickListener(this);
    }

    private void setAdapter() {
        search_list.addItemDecoration(new Divider(mContext));
        search_list.setLayoutManager(mLayoutManager);
        search_list.setAdapter(mAdapter);
    }

    @Override
    public void searchData(String searchKeyStr, String url) {
        if(TextUtils.isDigitsOnly(searchKeyStr)) {
            return;
        }
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));
        params.put("clientName", searchKeyStr);
        params.put("currentPage", 0);
        params.put("pageNum", 9999);
        httpManager.get(url, params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                final JiekuanrenResp resp = JSONUtil.parseObject(respStr, JiekuanrenResp.class);
                if (resp != null && resp.getDataList() != null) {
                    mList.clear();
                    mList.addAll(resp.getDataList());
                    notifyUpdateView();
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }

    @Override
    public void observerSearchText(List<JiekuanrenModel> list, String text) {
        if (this.getVisibility() == GONE) {
            this.setVisibility(VISIBLE);
        }
        if (list == null || list.size() < 1 || TextUtils.isEmpty(text)) {
            mList.clear();
            if(search_list.getParent() != null) {
                ((ViewGroup) search_list.getParent()).removeAllViews();
            }
            search_layout.removeAllViews();
            search_layout.addView(search_list);
            mAdapter.notifyDataSetChanged();
            return;
        }
        mList.clear();
        for (int i = 0; i < list.size(); i++) {
            JiekuanrenModel jiekuanrenModel = list.get(i);
            if (jiekuanrenModel.getSerialNumber().contains(text) || jiekuanrenModel.getClientName().contains(text)) {
                mList.add(jiekuanrenModel);
            }
        }
        if(search_list.getParent() != null) {
            ((ViewGroup) search_list.getParent()).removeAllViews();
        }
        search_layout.removeAllViews();
        search_layout.addView(search_list);
        mAdapter.notifyDataSetChanged();
    }

    private void notifyUpdateView() {
        if(mList.size() < 1) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.view_blank,null);
            search_layout.removeAllViews();
            search_layout.addView(view);
        } else {
            if(search_list.getParent() != null) {
                ((ViewGroup) search_list.getParent()).removeAllViews();
            }
            search_layout.removeAllViews();
            search_layout.addView(search_list);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void setListener(ViewItemListener viewItemListener, int itemType) {
        mViewItemListener = viewItemListener;
        curItemType = itemType;
    }

    @Override
    public void onClickListener(View view, int position) {
        if (mViewItemListener != null) {
            mViewItemListener.onItemClick(view, mList.get(position));
        }
    }

    public interface ViewItemListener {
        public void onItemClick(View view, Object object);
    }
}
